//
//  THEditTool.m
//  THImageEditDemo
//
//  Created by 希达 on 2018/3/30.
//  Copyright © 2018年 Tan.huang. All rights reserved.
//

#import "THEditTool.h"
#import "THImageTool.h"
#import "THScratchCardView.h"

#import "THGridLayar.h"
#import "THClippingPanel.h"

#import "THBottomTool.h"



typedef enum : NSUInteger {
    THEditToolEdit,
    THEditToolCrop,
    THEditToolAdvanced,
    THEditToolCutOut,
    THEditToolScale,
    THEditToolOneClick,
} THEditToolType;


@interface THEditTool ()
/// Edit 选择
@property (weak, nonatomic) THImageTool *editTool;
/// Crop 选择
@property (weak, nonatomic) THImageTool *cropTool;
/// Advanced 选择
@property (weak, nonatomic) THImageTool *advancedTool;
/// cut out
@property (weak, nonatomic) THImageTool *cutOutTool;
/// Scale
@property (weak, nonatomic) THImageTool *scaleTool;
/// One-click
@property (weak, nonatomic) THImageTool *oneClickTool;

@property (weak, nonatomic) THBottomTool *bottomTool;

@property (weak, nonatomic) THClippingPanel *gridView;

/// 背景图
@property (weak, nonatomic) UIImageView *bgImgView;
@property (weak, nonatomic) UIImageView *scratchBgImageView;
@property (weak, nonatomic) THScratchCardView *scratchView;
/// 刮出来的图片
@property (strong, nonatomic) UIImage *scratchImage;


@property (strong, nonatomic) UIImage *originalImage;
//@property (strong, nonatomic) UIImage *thumbnailImage;
@property (copy, nonatomic) NSString *cropTitle;


@property (assign, nonatomic) THEditToolType type;


@property (strong, nonatomic) UIImage *invertImage;
@property (strong, nonatomic) UIImage *bgInvertImage;

/// 是否反切
@property (assign, nonatomic) BOOL  isInvert;
/// 点击手势
@property (weak, nonatomic) UITapGestureRecognizer *tapRecognizer;
@end

@implementation THEditTool

- (void)dealloc {
    NSLog(@"%@释放了", NSStringFromClass(self.class));
}

#pragma mark - open
- (void)setup {
    [super setup];
    _originalImage = [self.editor.imageView.image fixOrientation];
//    _thumbnailImage = [UIImage imageWithCGImage:_originalImage.CGImage];

    [self configEditTool];
    [self configBtn];

    [self affineTransformScale:nil toView:self.bgView isShow:YES];
}

- (void)cleanup {
    [self affineTransformScale:nil toView:self.bgView isShow:NO];
    self.bgImgView.hidden = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgView removeFromSuperview];
        [self.bgImgView removeFromSuperview];
        [self.workingView removeFromSuperview];
    });
}


#pragma mark - 底部按钮
- (void)configBtn {
    THBottomTool *bottomTool = [[THBottomTool alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.editTool.frame), self.editor.view.tz_width, 44)];
    [self.bgView addSubview:bottomTool];
    self.bottomTool = bottomTool;

    @weakify(self);
    [bottomTool setDidBottomBackBtnClickBlock:^{
        @strongify(self);
        self.editor.titleName = @"";
        self.editor.imageView.image = self.originalImage;
        [self.editor refreshTool];
    }];
    [bottomTool setDidBottomDoneBtnClickBlock:^{
        @strongify(self);
        [self bottomToolDoneBtnClick];
    }];
    [bottomTool setDidBottomCancelBtnClickBlock:^{
        @strongify(self);
        [self bottomToolCancelBtnClick];
    }];
}

- (void)bottomToolDoneBtnClick {
    self.editor.titleName = @"";
    self.editor.imageView.image = self.originalImage;
    switch (self.type) {
        case THEditToolCrop: {
            [self gropDoneClick];
        } break;
        case THEditToolScale: {

        } break;
        case THEditToolCutOut: {
            [self cutOutDoneClick];
        } break;
        case THEditToolAdvanced:{
            [self advancedDoneClick];
        } break;
        case THEditToolOneClick: {
            [self oneClickDoneClick];
        } break;
        default: break;
    }
    [self.editor refreshTool];
}

- (void)bottomToolCancelBtnClick {
    switch (self.type) {
        case THEditToolCrop: {
            self.editor.titleName = @"Edit";
            self.bottomTool.leftTitle = @"Back";
            [self gropCancelClick];
        } break;
        case THEditToolScale: {

        } break;
        case THEditToolCutOut: {
            self.editor.titleName = @"Edit";
            self.bottomTool.leftTitle = @"Back";
            [self cutOutCancelClick];
        } break;
        case THEditToolAdvanced:{
            self.editor.titleName = @"Cut out";
            [self advancedCancelClick];
        } break;
        case THEditToolOneClick: {
            self.editor.titleName = @"Cut out";
            [self oneClickCancelClick];
        } break;
        default: break;
    }
}


- (void)configEditDone {

}


#pragma mark - EditTool
- (void)configEditTool {
    self.type = THEditToolEdit;
    CGFloat width = self.bgView.frame.size.width;
    CGFloat height = (width - 50) / 4;
    THImageTool *editTool = [[THImageTool alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), width, height)];
    self.editTool = editTool;
    self.editTool.titleArray = @[@"Crop", @"Cut out", @"Rotate/Scale"];
    self.editTool.imageArray = @[@"crop", @"cutting_coupon", @"connection_sync"];
    [self.editTool configView];
    [self.bgView addSubview:self.editTool];

    @weakify(self);
    self.editTool.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        @strongify(self);
        self.editor.titleName = title;
        if ([title isEqualToString:@"Crop"]) {
            [self configCropTool];
        } else if ([title isEqualToString:@"Cut out"]) {
            [self configCutOutTool];
        } else {

        }
    };
}

#pragma mark - CropTool
- (void)configCropTool {

    THClippingPanel *gridView = [[THClippingPanel alloc] initWithSuperview:self.editor.imageView.superview frame:self.editor.imageView.frame];
    _gridView = gridView;
    _gridView.backgroundColor = [UIColor clearColor];
    _gridView.bgColor = [self.editor.view.backgroundColor colorWithAlphaComponent:0.8];
    _gridView.gridColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.8];
    _gridView.clipsToBounds = NO;

    CGFloat width = self.bgView.frame.size.width;
    CGFloat height = (width - 50) / 4;
    THImageTool *cropTool = [[THImageTool alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), width, height)];
    self.cropTool = cropTool;
    self.cropTool.titleArray = @[@"Square", @"3:5", @"2:3", @"5:3", @"3:2"];
    self.cropTool.imageArray = @[@"Square", @"3-5", @"2-3", @"5-3", @"3-2"];
    [self.cropTool configView];
    [self.bgView addSubview:self.cropTool];

    self.type = THEditToolCrop;
    [self.bottomTool showDoneBtn];
    [self affineTransformScale:self.editTool toView:cropTool isShow:YES];

    __weak typeof(self) weakSelf = self;
    self.cropTool.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.editor.title = title;

        if (![strongSelf.cropTitle isEqualToString:title]) {
            strongSelf.cropTitle = title;
            NSArray *arr = [title componentsSeparatedByString:@":"];
            CGFloat ratio = 1;
            if (arr.count > 1) {
                ratio = [arr[1] floatValue] / [arr[0] floatValue];
            }
            strongSelf.gridView.clippingRatio = ratio;
        }
    };
}

- (void)gropDoneClick {
    
    CGFloat zoomScale = self.editor.imageView.frame.size.width / self.editor.imageView.image.size.width;
    CGRect rct = _gridView.clippingRect;
    rct.size.width  /= zoomScale;
    rct.size.height /= zoomScale;
    rct.origin.x    /= zoomScale;
    rct.origin.y    /= zoomScale;

    self.originalImage = [self.editor.imageView.image crop:rct];
    self.editor.imageView.image = self.originalImage;
    
    [self.editor resetImageViewFrame];
    [self.editor refreshTool];
    
    [self gropCancelClick];
}

- (void)gropCancelClick {
    [self.bottomTool hiddenDoneBtn];
    [self affineTransformScale:self.editTool toView:self.cropTool isShow:NO];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.gridView removeFromSuperview];
        [self.cropTool removeFromSuperview];
    });
}


#pragma mark - CutOutTool
- (void)configCutOutTool {
    CGFloat width = self.bgView.frame.size.width;
    CGFloat height = (width - 50) / 4;
    THImageTool *cutOutTool = [[THImageTool alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), width, height)];
    self.cutOutTool = cutOutTool;
    self.cutOutTool.isSeparate = true;
    self.cutOutTool.titleArray = @[@"One-click", @"Advanced"];
    self.cutOutTool.imageArray = @[@"finger_and_thumb", @"erase_image",];
    [self.cutOutTool configView];
    [self.bgView addSubview:self.cutOutTool];

    @weakify(self);
    self.cutOutTool.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        @strongify(self);
        self.editor.titleName = title;
        if ([title isEqualToString:@"One-click"]) {
            [self configOneClickTool];
        } else {
            [self configAdvancedTool];
        }
    };

    self.type = THEditToolCutOut;
    [self.bottomTool showDoneBtn];
    [self affineTransformScale:self.editTool toView:self.cutOutTool isShow:YES];

    UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.editor.scrollView.bounds];
    self.bgImgView = bgImgView;
    self.bgImgView.image = self.bgImage;
    [self.editor.scrollView insertSubview:self.bgImgView atIndex:0];

    /// 提前获取主图的纯白图片和背景图的透明度
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.invertImage = [self.originalImage drawImageWithTintColor:[UIColor whiteColor]];
        self.bgInvertImage = [self.bgImage changeImageWithAlpha:0.3];
    });
}


- (UIColor *)colorOfView:(UIView *)view point:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [view.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    return color;
}

- (void)cutOutDoneClick {

    UIImage *image = [self capture:self.editor.scrollView];
    self.editor.imageView.image = image;
    
    [self.editor resetImageViewFrame];
    [self.editor refreshTool];
    
    [self cutOutCancelClick];
}

- (void)cutOutCancelClick {
    [self.bottomTool hiddenDoneBtn];
    self.bgImgView.hidden = YES;
    [self affineTransformScale:self.editTool toView:self.cutOutTool isShow:NO];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.cutOutTool removeFromSuperview];
        [self.bgImgView removeFromSuperview];
    });
}


#pragma mark - ScaleTool
- (void)configScaleTool {
    self.type = THEditToolScale;
//    [self showDoneBtn];

}

#pragma mark - OneClickTool
- (void)configOneClickTool {

    CGFloat width = self.bgView.frame.size.width;
    CGFloat height = (width - 50) / 4;
    THImageTool *oneClickTool = [[THImageTool alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), width, height)];
    self.oneClickTool = oneClickTool;
    self.oneClickTool.titleArray = @[@"Invert cutout"];
    self.oneClickTool.imageArray = @[@"invert_selection"];
    self.oneClickTool.imageSelectArr = @[@"invert_selection_filled"];
    [self.oneClickTool configView];
    [self.bgView addSubview:self.oneClickTool];

    __weak typeof(self) weakSelf = self;
    self.oneClickTool.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf invertCutoutClick:isSelect];
    };

    self.bgImgView.userInteractionEnabled = true;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgImageViewTapClick:)];
    self.tapRecognizer = tap;
    [self.bgImgView addGestureRecognizer:tap];

    self.type = THEditToolOneClick;
    [self affineTransformScale:self.cutOutTool toView:self.oneClickTool isShow:YES];
}


- (void)bgImageViewTapClick:(UITapGestureRecognizer *)recognizer {
    CGRect frame = self.editor.imageView.frame;
    CGPoint location = [recognizer locationInView:recognizer.view];
    BOOL isPoint = CGRectContainsPoint(frame, location);
    if (isPoint) {
        CGPoint location1 = [recognizer.view convertPoint:location toView:self.editor.imageView];
        UIColor *color = [self colorOfView:self.editor.imageView point:location1];
        if (CGColorEqualToColor(color.CGColor, [UIColor colorWithRed:0 green:0 blue:0 alpha:0].CGColor)) {
            self.isInvert = false;
            self.editor.imageView.image = self.invertImage;
            self.bgImgView.image = self.bgImage;
        } else {
            self.isInvert = true;
            self.editor.imageView.image = self.originalImage;
            self.bgImgView.image = self.bgInvertImage;
        }
    } else {
        self.isInvert = false;
        self.editor.imageView.image = self.invertImage;
        self.bgImgView.image = self.bgImage;
    }

    /// 点击图片重置选中状态
    for (UIView *view in self.oneClickTool.subviews) {
        if ([view isKindOfClass:UIButton.class]) {
            UIButton *btn = (UIButton *)view;
            btn.selected = false;
        }
    }
}

- (void)oneClickCancelClick {
    self.type = THEditToolCutOut;

    self.editor.imageView.image = self.originalImage;
    self.bgImgView.image = self.bgImage;
    [self.bgImgView removeGestureRecognizer:self.tapRecognizer];
    
    [self affineTransformScale:self.cutOutTool toView:self.oneClickTool isShow:NO];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.oneClickTool removeFromSuperview];
    });
}

- (void)oneClickDoneClick {
    [self oneClickCancelClick];

    self.originalImage = [self capture:self.editor.scrollView];
    self.editor.imageView.image = self.originalImage;
    self.editor.imageView.frame = self.editor.scrollView.bounds;
    
    [self.editor resetImageViewFrame];
    [self.editor refreshTool];
    
    [self oneClickCancelClick];
}

- (void)invertCutoutClick:(BOOL)isSelect {
    if (self.isInvert) {
        self.editor.imageView.image = isSelect ? self.invertImage :  self.originalImage;
        self.bgImgView.image = isSelect ? self.bgImage : self.bgInvertImage;
    } else {
        self.editor.imageView.image = isSelect ? self.originalImage :  self.invertImage;
        self.bgImgView.image = isSelect ? self.bgInvertImage : self.bgImage;
    }
}

#pragma mark - AdvancedTool
- (void)configAdvancedTool {
    self.bgImgView.hidden = true;
    CGFloat width = self.bgView.frame.size.width;
    CGFloat height = (width - 50) / 4;
    THImageTool *advancedTool = [[THImageTool alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), width, height)];
    self.advancedTool = advancedTool;
    self.advancedTool.titleArray = @[@"Select", @"Invert cutout", @"Erase"];
    self.advancedTool.imageArray = @[@"border_color", @"invert_selection", @"erase"];
    self.advancedTool.imageSelectArr = @[@"border_color_filled", @"invert_selection_filled", @"erase_filled"];
    [self.advancedTool configView];
    [self.bgView addSubview:self.advancedTool];

    [self configScratchView];

    @weakify(self);
    self.advancedTool.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        @strongify(self);
        if ([title isEqualToString:@"Select"]) {
            self.scratchView.userInteractionEnabled = true;
            [self scratchViewWithStrokeColor:[UIColor blackColor] lineWidth: 20 isErase: false];
        } else if ([title isEqualToString:@"Invert cutout"]) {
            self.editor.imageView.image = isSelect ? self.invertImage : self.originalImage;
        } else {
            [self scratchViewWithStrokeColor:[UIColor clearColor] lineWidth: 20 isErase:true];
        }
    };

    self.type = THEditToolAdvanced;
    [self affineTransformScale:self.cutOutTool toView:self.advancedTool isShow:YES];
}
/// cancel 点击
- (void)advancedCancelClick {
    self.type = THEditToolCutOut;
    self.bgImgView.hidden = NO;
    [self affineTransformScale:self.cutOutTool toView:self.advancedTool isShow:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.scratchView removeFromSuperview];
        [self.advancedTool removeFromSuperview];
    });
}
/// done 点击
- (void)advancedDoneClick {

    self.originalImage = [self capture:self.editor.scrollView];
    
    self.editor.imageView.image = self.originalImage;
    self.editor.imageView.frame = self.editor.scrollView.bounds;

    [self affineTransformScale:self.cutOutTool toView:self.advancedTool isShow:NO];
    
    [self advancedCancelClick];
    
    [self.editor resetImageViewFrame];
    [self.editor refreshTool];
    
    [self oneClickCancelClick];
}

- (void)configScratchView {

    if (self.scratchView) {
        return;
    }
    self.editor.imageView.image = self.originalImage;
    [self.editor resetImageViewFrame];

    CGRect bounds = self.editor.scrollView.bounds;

    UIImageView *scratchBgImageView1 = [[UIImageView alloc] initWithFrame:bounds];
    scratchBgImageView1.image = self.bgImgView.image;

    UIImageView *scratchBgImageView = [[UIImageView alloc] initWithFrame:bounds];
    self.scratchBgImageView = scratchBgImageView;
    self.scratchBgImageView.userInteractionEnabled = true;
    self.scratchBgImageView.image = self.scratchImage ? self.scratchImage : [scratchBgImageView1.image changeImageWithAlpha:0.3];

    THScratchCardView *scratchView = [[THScratchCardView alloc] initWithFrame:bounds];
    self.scratchView = scratchView;
    self.scratchView.userInteractionEnabled = false;
    [self.scratchView.coverViewContainer addSubview:scratchBgImageView];
    [self.scratchView.contentViewContainer addSubview:scratchBgImageView1];

    [self.editor.scrollView addSubview:self.scratchView];
    [self.editor.scrollView addSubview:self.editor.imageView];
}


- (void)scratchViewWithStrokeColor:(UIColor *)strokeColor lineWidth:(CGFloat)lineWidth isErase:(BOOL)isErase{
    self.scratchView.lineWidth = lineWidth;
    self.scratchView.strokeColor = strokeColor;
    self.scratchView.isErase = isErase;
}

#pragma mark - 私有方法


/// 绘制带背景的图片
//- (UIImage *)getWaterMarkImage:(UIImageView *)originalImgView bgimgView:(UIImageView *)bgimgView {
//    CGFloat ratio = self.editor.ratio;
//    CGFloat bgWidth = bgimgView.width;
//    CGFloat bgHeight = bgimgView.height;
//    //为了防止图片失真，绘制区域宽高和原始图片宽高一样
//    UIGraphicsBeginImageContext(CGSizeMake(bgWidth / ratio, bgHeight / ratio));
//    //先将原始image绘制上
//    [bgimgView.image drawInRect:CGRectMake(0, 0, bgWidth / ratio, bgHeight / ratio)];
//    [originalImgView.image drawInRect:CGRectMake(originalImgView.left / ratio, originalImgView.top / ratio, originalImgView.width / ratio, originalImgView.height / ratio)];
//    //根据上下文制作成图片
//    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return finalImg;
//}

@end



